package com.javasea.web.servlet;

import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@WebServlet(urlPatterns = "/myservlet")
public class MyServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Map<String, String[]> parameterMap = req.getParameterMap();
        Map<String, Object> map = new HashMap<>();
        for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
            String[] value = entry.getValue();
            if(value.length == 1){
                map.put(entry.getKey(), value[0]);
            } else {
                map.put(entry.getKey(), value);
            }
        }
        String s = JSON.toJSONString(map);
        System.out.println(s);

        System.out.println(JSON.toJSONString(parameterMap));
        resp.getWriter().println("My SpringBoot Servlet-1");
        resp.getWriter().flush();
        resp.getWriter().close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("name");
        System.out.println(name);

        resp.getWriter().println("My SpringBoot Servlet-1");
        resp.getWriter().flush();
        resp.getWriter().close();
        doGet(req, resp);
    }
}
